import java.io.IOException;

/** 
 	Class To Represent a CPU
   	@author Morton and Uemura
 */

public class CPU {
	
	/** Process in CPU */
	private Process process;
	
	/** Indicator for Currently Processing or not */
	private boolean empty;

	
	/**
	    Constructs a CPU with no Process
	 */
	public CPU()
	{
		empty = true;
		try 
		{
			process = new Process(null, -1, -1, -1, -1, -1, -1, -1, -1, 0);
		} 
		catch (IOException e) 
		{ // Never Reached
		}
	}
	
	
	/**
	   Returns true if CPU has no Process
	   @return true if empty, else false
	 */
	public boolean isEmpty()
	{
		return this.empty;
	}
	
	
	/**
	   CPU takes an incoming Process
	   @param incoming Process to be processed
	 */
	public void put(Process incoming)
	{
		process = incoming;
		process.setAddedToCPU(true);
		empty = false;
	}
	
	
	/**
	   Returns a Process from the CPU based on 
	    specified current clock time
	   @param clockTime current clock time
	   @return current Process in CPU, null if none
	 */
	public Process update(double tick)
	{
		// Check if empty
		if (empty) return null;
		// Update Process remaining time (CPU run simulation)
		process.decrementRemainingTime(tick);
		if (process.getCurrentTimeSlice() <= 0)
			process.setFeedback(true);
		return process;
	}
	
	
	/**
	   Preempts current Process
	   @return preempted Process 
	 */
	public Process preempt()
	{
		return process;
	}
	
	
	/**
	   Determines if current process in CPU must be 
	    pre-empted out for the next incoming process.
	    That is, if next process is of high priority.
	    If CPU is empty, returns true always.
	   @param nextProcess next process to CPU
	   @return true if next process is higher priority
	    than current process in CPU
	 */
	public boolean isReady(Process nextProcess)
	{
		if (empty)
			return true;
		else if (nextProcess.getCurrentQueueNumber() <
				process.getCurrentQueueNumber())
			return true;
		else
			return false;
	}
}
